package rxjava2.groccery;


import io.reactivex.*;
import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Consumer;
import io.reactivex.functions.Function;

/**
 * Created by SEELE on 2018/8/6.
 */
public class onXX {
    public static void main(String[] args) {

        //失败之后并不会调用onError,而是依然调用onNext，传递 自定义的消息内容
//        onErrorReturnItem();
        //发生错误，调用另外一个ob
        onErrorResumeNext();
    }

    private static void onErrorResumeNext() {

        getErrorOb().onErrorResumeNext(new Function<Throwable, ObservableSource<? extends String>>() {
            public ObservableSource<? extends String> apply(final Throwable throwable) throws Exception {
                return Observable.create(new ObservableOnSubscribe<String>() {
                    public void subscribe(ObservableEmitter<String> e) throws Exception {
                        e.onNext(throwable.getLocalizedMessage());
                        e.onComplete();
                    }
                });
            }
        }).subscribe(new Consumer<String>() {
            public void accept(String s) throws Exception {
                System.out.println(s);
            }
        });

    }

    private static void onErrorReturnItem() {
        getErrorOb().onErrorReturnItem("you should have received A_ error,but now received cute me")
                .subscribe(new Observer<String>() {
                    public void onSubscribe(Disposable d) {

                    }

                    public void onNext(String value) {
                        System.out.println(value);
                    }

                    public void onError(Throwable e) {
                        System.out.println(e.getMessage());
                    }

                    public void onComplete() {

                    }
                });
    }

    public static Observable<String> getErrorOb() {
        return Observable.create(new ObservableOnSubscribe<String>() {
            public void subscribe(ObservableEmitter<String> e) throws Exception {
                e.onError(new IllegalStateException("nifty error"));
            }
        });
    }
}
